import React, { useState, useCallback } from 'react'

export interface FileUploadProps {
  onUpload?: (files: File[]) => Promise<void> | void
  accept?: string
  multiple?: boolean
  disabled?: boolean
  label?: React.ReactNode
  description?: React.ReactNode
}

export default function FileUpload({
  onUpload,
  accept = '',
  multiple = false,
  disabled = false,
  label = '点击上传或拖拽文件到此',
  description = ''
}: FileUploadProps) {
  const [isUploading, setIsUploading] = useState(false)
  const [uploadProgress, setUploadProgress] = useState(0)
  const [uploadStatus, setUploadStatus] = useState('')

  const handleFiles = useCallback(
    async (files: File[]) => {
      if (!onUpload || files.length === 0) return
      setIsUploading(true)
      setUploadProgress(0)
      setUploadStatus('正在上传...')
      try {
        await onUpload(files)
        setUploadProgress(100)
        setUploadStatus('上传完成！')
      } catch (e) {
        setUploadStatus('上传失败，请重试')
      } finally {
        setTimeout(() => {
          setIsUploading(false)
          setUploadProgress(0)
          setUploadStatus('')
        }, 1000)
      }
    },
    [onUpload]
  )

  const handleFileUpload = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const files = Array.from(event.target.files || [])
    if (files.length === 0) return
    await handleFiles(files)
    event.target.value = ''
  }

  const handleDrop = async (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault()
    const files = Array.from(event.dataTransfer.files)
    if (files.length === 0) return
    await handleFiles(files)
  }

  const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault()
  }

  return (
    <div
      className={`group relative mt-1 w-full max-w-2xl cursor-default rounded-lg border border-dashed border-gray-300 bg-white p-2 shadow-sm transition-all duration-200 hover:shadow-md ${
        isUploading ? 'pointer-events-none opacity-50' : ''
      }`}
      onDrop={handleDrop}
      onDragOver={handleDragOver}
    >
      <input
        type="file"
        multiple={multiple}
        onChange={handleFileUpload}
        className="hidden"
        id="file-upload"
        accept={accept}
        disabled={isUploading || disabled}
      />
      <label
        htmlFor="file-upload"
        className="flex cursor-pointer select-none flex-col items-center justify-center"
      >
        <span className="mb-1 flex items-center justify-center">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            className="size-7 text-gray-400 group-hover:text-gray-600"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 10l5-5m0 0l5 5m-5-5v12"
            />
          </svg>
        </span>
        <span className="text-sm font-medium text-gray-400 group-hover:text-gray-500">
          {isUploading ? '正在上传中...' : label}
        </span>
        {description && (
          <span className="mt-1 text-xs text-gray-300">
            {isUploading ? '请稍候，正在处理您的文件' : description}
          </span>
        )}
      </label>
      <div className="pointer-events-none absolute inset-0 rounded-lg border-2 border-transparent transition-all duration-200 group-hover:border-gray-200"></div>
      {/* 上传进度条 */}
      {isUploading && (
        <div className="fixed left-1/2 top-4 z-50 w-full max-w-md -translate-x-1/2 px-4">
          <div className="rounded-lg border bg-white p-4 shadow-lg duration-300 animate-in slide-in-from-top-2">
            <div className="mb-2 flex items-center justify-between">
              <span className="text-sm font-medium text-gray-700">
                {uploadStatus}
              </span>
              <span className="text-sm text-gray-500">{uploadProgress}%</span>
            </div>
            <div className="h-2 w-full rounded bg-gray-200">
              <div
                className="h-2 rounded bg-blue-500"
                style={{ width: `${uploadProgress}%` }}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
